import {Injectable} from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class DaDataService {

  constructor() { }
  result?: any
  geo_lat?: string
  geo_lon?: string
  qc_geo?: string
  address?: string
  url = "http://suggestions.dadata.ru/suggestions/api/4_1/rs/suggest/address"
  token = "fc4e8b7eb51ed3b241ee3f896dd2107c52df1405"
  query = ''

  options = {
    method: "POST",
    mode: "cors",
    headers: {
      "Content-Type": "application/json",
      "Accept": "application/json",
      "Authorization": "Token " + this.token
    },
    body: JSON.stringify({query: this.query})
  }


  getAddressData(ads: string) {

    let options = {
      method: "POST",
      mode: "cors",
      headers: {
        "Content-Type": "application/json",
        "Accept": "application/json",
        "Authorization": "Token " + this.token
      },
      body: JSON.stringify({query: ads, count: 1})
    }
    // @ts-ignore
    fetch(this.url, options)
      .then(response => response.text())
      // .then(result => console.log(result))
      .then(result => this.result = result)
      .catch(error => console.log("error", error));
  }

  getResult() {
    let res = JSON.parse(this.result)
    // console.log(res)
    this.geo_lat = res.suggestions[0].data.geo_lat
    this.geo_lon = res.suggestions[0].data.geo_lon
    this.qc_geo = res.suggestions[0].data.qc_geo
    this.address = res.suggestions[0].value
    console.log(this.address)
    let temp = {
      geo_lat: this.geo_lat,
      geo_lon: this.geo_lon,
      qc_geo: this.qc_geo,
      address: this.address
    }
    return JSON.stringify(temp)
  }
}
